package Mapper

import (
	"fmt"
	"time"
)

type AddressServiceMapperType struct {
	Services []string
	UpdateAt time.Time
}

type ServiceAddressMapperType struct {
	Addresses []string
}

var AddressServiceMapper map[string]*AddressServiceMapperType
var ServiceAddressMapper map[string]*ServiceAddressMapperType

// InitMapper map这里使用的是程序空间
// 当然也可以使用Redis来作为地址服务映射，以便进行集群化管理
func InitMapper() {
	AddressServiceMapper = make(map[string]*AddressServiceMapperType)
	ServiceAddressMapper = make(map[string]*ServiceAddressMapperType)
}

func CheckUpdateAtProcess() {
	fmt.Printf("%d %+v %+v\n", time.Now().Unix(), AddressServiceMapper, ServiceAddressMapper)
	for k, v := range AddressServiceMapper {
		if time.Now().Unix()-v.UpdateAt.Unix() > 30 {
			for _, service := range v.Services {
				var index int
				var objAddress string
				for index, objAddress = range ServiceAddressMapper[service].Addresses {
					if objAddress == k {
						break
					}
				}
				ServiceAddressMapper[service].Addresses = append(ServiceAddressMapper[service].Addresses[:index],
					ServiceAddressMapper[service].Addresses[index+1:]...)
			}
			delete(AddressServiceMapper, k)
		}
	}
}

func CheckHeartBeat(address string) {
	AddressServiceMapper[address].UpdateAt = time.Now()
}
